<?php
/**
 * 微信授权
 */
$appid  = 'wx215a19515f61a28c';
$secret = 'aee4b9dd41559908f444b91b9f28cf5d';
$state  = $_GET['state'];// 订单号
$url    = 'https://' . $_SERVER['HTTP_HOST'] . '/hongbao/?oid=' . $state;
if ($_COOKIE['lh_wxtk']) {
    header("Location: $url");
}

if (isset($_GET['code'])) {
    $api  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$_GET['code']}&grant_type=authorization_code";
    $json = httpReq($api);
    $arr  = json_decode($json, true);
    if (isset($arr['errcode'])) die($arr['errcode'] . ':' . $arr['errmsg']);

    $wxtk = base64_encode($arr['access_token'] . '|' . $arr['openid']);
    setcookie('lh_wxtk', $wxtk, time() + 5000, '/', '', 1, 1);
    header("Location: $url");

} else {
    if (!$state) die('Access Denied');
    $param = [
        'appid'         => $appid,
        'redirect_uri'  => 'https://' . $_SERVER['HTTP_HOST'] . '/wxoauth.php',
        'response_type' => 'code',
        'scope'         => 'snsapi_userinfo',
        'state'         => $state,
    ];
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query($param) . '#wechat_redirect';
    header("Location: $url");
}

// http请求
function httpReq($url, $data = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
    if ($data) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}